package kr.hyunist.androidcomplete01saeildamil.ch19;

import kr.hyunist.androidcomplete01saeildamil.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.TextView;

public class BackWorkEx03 extends Activity {
	TextView mResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.backworkex);

		mResult = (TextView) findViewById(R.id.backworkstarttv);
	}

	public void mOnClick(View v) {
		int start = 0, end = 100;
		int result;

		WaitDlg dlg = new WaitDlg(BackWorkEx03.this, "Wait", "Now Calculating..");
		dlg.start();
		
		result = AccumThread(start, end);
		mResult.setText("" + result);
		
		WaitDlg.stop(dlg);
	}

	private int AccumThread(int start, int end) {
		int sum = 0;
		
		for(int i = start; i <= end; i++){
			sum += i;
			
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		return sum;
	}

}



class WaitDlg extends Thread {
	Context mContext;
	String mTitle;
	String mMsg;
	ProgressDialog mProgress;
	Looper mLoop;

	public WaitDlg(Context context, String title, String msg) {
		this.mContext = context;
		this.mTitle = title;
		this.mMsg = msg;
		
		setDaemon(true);
	}
	
	@Override
	public void run() {
		Looper.prepare();
		
		mProgress = new ProgressDialog(mContext);
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setTitle(mTitle);
		mProgress.setMessage(mMsg);
		mProgress.setCancelable(false);
		mProgress.show();
		
		mLoop = Looper.myLooper();
		
		Looper.loop();
	}

	static void stop(WaitDlg dlg){
		dlg.mProgress.dismiss();
		//대화 상자가 사라지기 전까지 대기
		
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		dlg.mLoop.quit();
	}
}